import cv2
import numpy as np

# 提取輪廓的函數
def extract_contours(mask_path):
    # 讀取遮罩圖片（灰度模式）
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
    
    # 檢查是否成功讀取
    if mask is None:
        print(f"Failed to read {mask_path}")
        return None
    
    # 提取輪廓
    contours, hierarchy = cv2.findContours(
        mask, 
        cv2.RETR_EXTERNAL,  # 只提取外部輪廓
        cv2.CHAIN_APPROX_SIMPLE  # 壓縮水平、垂直和對角線的冗餘點
    )
    
    return contours, hierarchy

# 測試：讀取之前保存的遮罩並提取輪廓
for i in range(1):  # 假設有 3 個遮罩
    mask_path = "/home/JSDC/017254/code/gitee/deep-learing/masks/mask_0.png"  # 遮罩文件名
    contours, hierarchy = extract_contours(mask_path)


    contour = contours[0]

    for i in range(contour.shape[0]):
        xy = contour[i]
        print(xy)

    
    if contours is not None:
        print(f"Mask {i}: Found {len(contours)} contours.")
        
        # 可視化輪廓
        # 創建一個空白圖像來繪製輪廓
        contour_image = np.zeros((768, 1024, 3), dtype=np.uint8)  # 與遮罩相同大小
        cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)  # 用綠色繪製輪廓
        
        # 保存輪廓可視化結果
        output_contour_path = f"contours/contour_{i}.png"
        cv2.imwrite(output_contour_path, contour_image)
        print(f"Saved contour visualization for mask {i} as {output_contour_path}")
